<template>
  <el-select
    ref="select"
    :multiple="isMultiple"
    v-model="selectedValue"
    filterable
    remote
    clearable
    :remote-method="remoteMethod"
    :loading="loading"
    @change="onChange"
    :disabled="disabled"
    style="width: 80%"
    placeholder="请输入商品名称或条码"
  >
    <el-option
      :disabled="option.isBind"
      v-for="option in options"
      :label="option.label"
      :key="option.value"
      :value="option.value"
      >{{ option.label }}</el-option
    >
  </el-select>
</template>
<script>
import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
export default {
  props: {
    // disabled: Boolean,
    url: String,
    queryParamers: {
      type: Object,
      default: () => {},
    },
    isMultiple: {
      type: Boolean,
      default: false,
    },
    queryName: String,
    businessId: Number,
  },
  data() {
    return {
      selectedValue: "",
      loading: false,
      options: [],
      disabled: false,
      selectedOptions: [],
    };
  },
  watch: {
    queryName(val, oldval) {
      this.$nextTick(() => {
        this.selectedValue = val;
        this.$forceUpdate();
      });
    },
  },
  mounted() {
    // console.log(this.queryName);
  },
  methods: {
    changeName(val) {
      this.setQuery(val);
    },
    clear() {
      // this.$refs['select'].clearSingleSelect()
      this.selectedValue = "";
    },
    setQuery(val) {
      this.$refs["select"].setQuery(val);
    },
    remoteMethod(query) {
      // console.log(query);
      if (query === "") {
        this.options = [];
        return;
      }
      this.loading = true;
      const data = {
        keyword: query,
        businessId:this.businessId
      };
      for (let key in this.queryParamers) {
        data[key] = this.queryParamers[key];
      }
      axios
        .request({
          url: process.env.VUE_APP_BASE_API + this.url,

          method: "get",
          params: data,
          headers: {
            marketId: store.state.app.marketId,
            Authorization: getToken(),
          },
        })
        .then((res) => {
          // console.log(res);
          let data = res.data.data;
          if(data==null){
            data=[]
          }
          // console.log(data);
          let items = [];
          for (let item of data) {
            let isBind = false;
            if ("isBind" in item) {
              isBind = item.isBind;
            }
            if(item.enterprise_code){
               items.push({
              value: item.enterprise_code,
              label: item.market_name,       
            });
            }
           if(item.unique_id){
               items.push({
              value: item.unique_id,
              label: item.product_name,
              product_id:item.product_id,
              productName:item.product_name,
              goodsCode:item.goods_code,
              goodsName:item.goods_name,
              barcode:item.barcode,
            });
            }
            if(item.source_id){
               items.push({
              value: item.source_id,
              label: item.name,
              source_type:item.source_type
            });
            }
          }
          // console.log(111);
          // console.log(items)
          this.options = items;
          this.loading = false;
          // console.log(this.options.length);
          if (this.options.length == 0) {
            this.options.push({ label: query, value: "999999",product_id:"999999",source_type:"999999"});
          }
        })
        .catch((_) => {
          this.loading = false;

          this.options = [];
        });
    },
    onChange(it) {
      if (this.isMultiple === true) {
        let newselectedValue = it.map((item) => ({ value: item }));

        let selectedOption = null;
        let finded = false;
        for (let ai of newselectedValue) {
          if (finded) {
            break;
          }
          for (let bi of this.options) {
            if (ai.value === bi.value) {
              selectedOption = bi;
              finded = false;
              break;
            }
          }
        }
        if (selectedOption != null) {
          let contan = false;
          for (let i of this.selectedOptions) {
            if (i.value == selectedOption.value) {
              contan = true;
            }
          }

          if (!contan) {
            this.selectedOptions.unshift(selectedOption);
          }
        }

        // 移除
        let notDeleted = [];
        for (let si of this.selectedOptions) {
          for (let v of it) {
            if (v == si.value) {
              notDeleted.unshift(si);
            }
          }
        }

        this.selectedOptions = notDeleted;

        console.log("selectedOptions", this.selectedOptions);

        // this.$emit('selected', this.selectedOptions)
        this.$emit("selected", it);
        console.log("over");
      } else {
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].value === this.selectedValue) {
            this.$emit("selected", this.options[i]);
            break;
          }
        }
      }
    },
  },
};
</script>
